from tortoise.models import Model
from tortoise import fields
from datetime import datetime


class Product(Model):
    """
    商品信息模型
    """
    pid = fields.IntField(pk=True, description="商品ID")
    pcode = fields.CharField(max_length=64, null=True, description="编号")
    pname = fields.CharField(max_length=64, null=True, description="商品名称")
    type = fields.CharField(max_length=20, null=True, description="类别")
    alias = fields.CharField(max_length=20, null=True, description="助记名")
    brand = fields.CharField(max_length=20, null=True, description="品牌")
    formulatext = fields.CharField(max_length=16, null=True, description="单位换算")
    formulanum = fields.IntField(default=0, description="大单位换算")
    smallunittype = fields.CharField(max_length=20, default="0.00", description="小单位类型")
    smallunit = fields.CharField(max_length=20, null=True, description="小单位")
    smallunitbarcode = fields.CharField(max_length=20, null=True, description="小单位条码")
    smallprice = fields.DecimalField(max_digits=10, decimal_places=2, null=True, description="小单位价格")
    bigunit = fields.CharField(max_length=20, null=True, description="大单位")
    bigunitbarcode = fields.CharField(max_length=20, null=True, description="大单位条码")
    bigprice = fields.DecimalField(max_digits=10, decimal_places=2, null=True, description="大单位价格")
    status = fields.CharField(max_length=20, default="0", description="货品状态")
    create_by = fields.CharField(max_length=64, null=True, description="创建者")
    create_time = fields.DatetimeField(null=True, description="创建时间")
    update_by = fields.CharField(max_length=64, null=True, description="更新者")
    update_time = fields.DatetimeField(null=True, description="更新时间")
    remark = fields.CharField(max_length=128, null=True, description="备注")
    del_flag = fields.CharField(max_length=1, default="0", description="删除标志(0代表存在 2代表删除)")

    class Meta:
        table = "wms_product"
        table_description = "商品信息表"

    def __str__(self):
        return f"Product(pid={self.pid}, pname={self.pname})"

    @property
    def is_active(self) -> bool:
        """判断商品是否激活"""
        return self.status == "0"

    @property
    def is_deleted(self) -> bool:
        """判断商品是否被删除"""
        return self.del_flag == "2"

    @classmethod
    async def get_active_products(cls):
        """获取所有激活的商品"""
        return await cls.filter(status="0", del_flag__not="2")

    @classmethod
    async def get_by_pname(cls, pname: str):
        """根据商品名称获取商品"""
        return await cls.filter(pname=pname, del_flag__not="2").first()